package com.softeem.ossmusic.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.softeem.ossmusic.comm.R;
import com.softeem.ossmusic.entity.MusicList;
import com.softeem.ossmusic.entity.MusicListDetails;
import com.softeem.ossmusic.service.MusicListDetailsService;
import com.softeem.ossmusic.service.MusicListService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Tag(name = "歌单管理")
@RestController
public class MusicListController {

    @Autowired
    private MusicListService musicListService;
    
    @Autowired
    private MusicListDetailsService musicListDetailsService;

    @Operation(summary = "歌单列表", description = "分页查询歌单列表")
    @Parameters({
            @Parameter(name = "page",description = "页码"),
            @Parameter(name = "limit",description = "数据条数")
    })
    @GetMapping("/musicList/list")
    public R list(@RequestParam(defaultValue = "1") Integer page,@RequestParam(defaultValue = "5")Integer limit){
        //创建分页对象
        IPage<MusicList> ipage = new Page<>(page, limit);
        //执行查询(分页)
        musicListService.page(ipage);
        //返回结果
        return R.success().setData(ipage.getRecords()).setCount(ipage.getTotal());
    }
    
    @Operation(summary = "歌单详情", description = "根据id查询歌单详情")
    @GetMapping("/musicList/details")
    public R details(Integer id){
        MusicList musicList = musicListService.getById(id);
        if(musicList == null){
            return R.error().setMsg("歌单不存在");
        }
        return R.success().setData(musicList);
    }
    
    @Operation(summary = "添加歌单", description = "添加新歌单")
    @PostMapping("/musicList/add")
    public R add(@RequestBody MusicList musicList){
        musicList.setCreateTime(new Date());
        if(musicListService.save(musicList)){
            return R.success().setMsg("添加成功").setData(musicList);
        }
        return R.error().setMsg("添加失败");
    }
    
    @Operation(summary = "修改歌单", description = "根据id修改歌单信息")
    @PutMapping("/musicList/update")
    public R update(@RequestBody MusicList musicList){
        if(musicList.getId() == null || musicListService.getById(musicList.getId()) == null){
            return R.error().setMsg("歌单不存在");
        }
        //保留原创建时间
        MusicList old = musicListService.getById(musicList.getId());
        musicList.setCreateTime(old.getCreateTime());
        
        if(musicListService.updateById(musicList)){
            return R.success().setMsg("修改成功");
        }
        return R.error().setMsg("修改失败");
    }
    
    @Operation(summary = "删除歌单", description = "根据id删除歌单")
    @DeleteMapping("/musicList/delete")
    public R delete(Integer id){
        if(id == null || musicListService.getById(id) == null){
            return R.error().setMsg("歌单不存在");
        }
        
        //先删除歌单详情（歌曲关联）
        musicListDetailsService.remove(
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<MusicListDetails>()
                .eq("music_list_id", id)
        );
        
        if(musicListService.removeById(id)){
            return R.success().setMsg("删除成功");
        }
        return R.error().setMsg("删除失败");
    }
    
    @Operation(summary = "获取用户歌单", description = "根据用户id查询其创建的歌单")
    @GetMapping("/musicList/user")
    public R getUserMusicList(Integer uid){
        if(uid == null){
            return R.error().setMsg("用户ID不能为空");
        }
        List<MusicList> list = musicListService.list(
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<MusicList>()
                .eq("uid", uid)
        );
        return R.success().setData(list);
    }
    
    @Operation(summary = "添加音乐到歌单", description = "将音乐添加到指定歌单")
    @PostMapping("/musicList/addMusic")
    public R addMusic(@RequestParam("mlid") Integer mlid, @RequestParam("musicIds") List<Integer> musicIds) {
        // 验证歌单是否存在
        if (mlid == null || musicListService.getById(mlid) == null) {
            return R.error().setMsg("歌单不存在");
        }
        
        // 验证音乐ID列表
        if (musicIds == null || musicIds.isEmpty()) {
            return R.error().setMsg("请选择要添加的音乐");
        }
        
        // 批量添加音乐到歌单
        try {
            for (Integer musicId : musicIds) {
                // 检查是否已存在该关联
                MusicListDetails existing = musicListDetailsService.getOne(
                    new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<MusicListDetails>()
                        .eq("list_id", mlid)
                        .eq("music_id", musicId)
                );
                
                if (existing == null) {
                    // 创建新的关联记录
                    MusicListDetails details = new MusicListDetails();
                    details.setListId(mlid);
                    details.setMusicId(musicId);
                    musicListDetailsService.save(details);
                }
            }
            return R.success().setMsg("添加成功");
        } catch (Exception e) {
            return R.error().setMsg("添加失败：" + e.getMessage());
        }
    }
}
